package com.lld.im.common.router.algorithm.random;

import com.lld.im.common.enums.UserErrorCode;
import com.lld.im.common.exception.ApplicationException;
import com.lld.im.common.router.RouterHandler;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 负载均衡-随机算法
 */
public class RandomRouterHandler implements RouterHandler {

    @Override
    public String getServer(List<String> severs, String id) {
        int size = severs.size();
        if(size==0){
            throw new ApplicationException(UserErrorCode.SERVER_NOT_AVAILABLE);
        }
        int i = ThreadLocalRandom.current().nextInt(size);
        return severs.get(i);
    }
}
